import { request } from '@/utils/request'
import type { ApiResponse } from '@/types/api'
import type { ExecutionResult } from './test-case'

// 测试计划接口（状态从状态管理系统动态获取）
export interface TestPlan {
  id: string
  name: string
  description?: string
  project_id: string
  start_date?: string
  end_date?: string
  status: string  // 状态代码，从状态管理系统获取
  test_case_ids: string[]
  creator_id: string
  pass_rate?: number
  created_at: string
  updated_at: string
}

export interface TestPlanCreate {
  name: string
  description?: string
  project_id: string
  start_date?: string
  end_date?: string
  status?: string  // 状态代码，从状态管理系统获取
  test_case_ids?: string[]
  creator_id?: string
}

export interface TestPlanUpdate {
  name?: string
  description?: string
  project_id?: string
  start_date?: string
  end_date?: string
  status?: string  // 状态代码，从状态管理系统获取
  test_case_ids?: string[]
}

export interface TestPlanListResponse extends TestPlan {
  project_name?: string
  test_case_count: number
  executed_count: number
  creator_name?: string
}

export interface TestPlanDetailResponse extends TestPlan {
  project_name?: string
  creator_name?: string
  test_cases: Array<{
    id: string
    title: string
    status: string
    priority: string
  }>
  executions: TestPlanExecutionResponse[]
  statistics: {
    total: number
    executed: number
    not_executed: number
    passed: number
    failed: number
    blocked: number
    skipped: number
    pass_rate?: number
  }
}

export interface TestPlanExecutionResponse {
  id: string
  test_plan_id: string
  test_case_id: string
  execution_result: ExecutionResult
  executed_by: string
  execution_date: string
  notes?: string
  attachments: string[]
  test_case_title?: string
  executed_by_name?: string
  created_at: string
  updated_at: string
}

export interface TestPlanExecuteRequest {
  test_case_id: string
  execution_result: ExecutionResult
  notes?: string
  attachments?: string[]
}

export interface TestPlanCompleteRequest {
  // 可以添加完成时的备注等字段
}

export interface TestPlanGenerateReportRequest {
  include_details?: boolean
}

// 分页列表响应类型
export interface PaginatedListResponse<T> {
  items: T[]
  total: number
  page: number
  size: number
}

// API函数
export function getTestPlans(params?: {
  project_id?: string
  status?: string  // 状态代码，从状态管理系统获取
  page?: number
  size?: number
}): Promise<PaginatedListResponse<TestPlanListResponse>> {
  const requestParams: any = {}
  if (params?.project_id) requestParams.project_id = params.project_id
  if (params?.status) requestParams.status = params.status
  if (params?.page) requestParams.skip = (params.page - 1) * (params.size || 20)
  if (params?.size) requestParams.limit = params.size

  return request.get('/test-plans', { params: requestParams }).then(response => {
    console.log('测试计划 API 原始响应:', response.data)
    
    if (response.data && response.data.success) {
      const data = response.data.data
      const pagination = response.data.pagination
      
      console.log('解析的数据:', data)
      console.log('解析的分页信息:', pagination)
      
      // 如果 data 是数组
      if (Array.isArray(data)) {
        // 如果有 pagination，使用分页信息
        if (pagination) {
          const result = {
            items: data,
            total: pagination.total || 0,
            page: pagination.page || 1,
            size: pagination.size || (params?.size || 20)
          }
          console.log('返回分页结果:', result)
          return result
        }
        // 如果没有 pagination，说明返回的是简单列表，设置默认分页信息
        const result = {
          items: data,
          total: data.length,
          page: params?.page || 1,
          size: params?.size || 20
        }
        console.log('返回简单列表结果:', result)
        return result
      }
      
      // 如果 data 是对象且包含 items（兼容其他格式）
      if (data && typeof data === 'object' && Array.isArray(data.items)) {
        const result = {
          items: data.items || [],
          total: data.total || 0,
          page: data.page || (params?.page || 1),
          size: data.size || (params?.size || 20)
        }
        console.log('返回对象格式结果:', result)
        return result
      }
    }
    
    // 默认返回空列表
    console.log('返回默认空列表')
    return {
      items: [],
      total: 0,
      page: params?.page || 1,
      size: params?.size || 20
    }
  })
}

export function getTestPlanById(id: string): Promise<ApiResponse<TestPlanDetailResponse>> {
  return request.get(`/test-plans/${id}`).then(response => {
    if (response.data && response.data.success) {
      return response.data
    }
    throw new Error(response.data?.message || '获取测试计划失败')
  })
}

export function createTestPlan(data: TestPlanCreate): Promise<ApiResponse<TestPlan>> {
  return request.post('/test-plans', data).then(response => {
    if (response.data && response.data.success) {
      return response.data
    }
    throw new Error(response.data?.message || '创建测试计划失败')
  })
}

export function updateTestPlan(id: string, data: TestPlanUpdate): Promise<ApiResponse<TestPlan>> {
  return request.put(`/test-plans/${id}`, data).then(response => {
    if (response.data && response.data.success) {
      return response.data
    }
    throw new Error(response.data?.message || '更新测试计划失败')
  })
}

export function deleteTestPlan(id: string): Promise<ApiResponse<null>> {
  return request.delete(`/test-plans/${id}`).then(response => {
    if (response.data && response.data.success) {
      return response.data
    }
    throw new Error(response.data?.message || '删除测试计划失败')
  })
}

export function executeTestCase(
  testPlanId: string,
  data: TestPlanExecuteRequest
): Promise<ApiResponse<TestPlanExecutionResponse>> {
  return request.post(`/test-plans/${testPlanId}/execute`, data).then(response => {
    if (response.data && response.data.success) {
      return response.data
    }
    throw new Error(response.data?.message || '执行测试用例失败')
  })
}

export function completeTestPlan(
  testPlanId: string,
  data: TestPlanCompleteRequest = {}
): Promise<ApiResponse<TestPlan>> {
  return request.post(`/test-plans/${testPlanId}/complete`, data).then(response => {
    if (response.data && response.data.success) {
      return response.data
    }
    throw new Error(response.data?.message || '完成测试计划失败')
  })
}

export function generateTestPlanReport(
  testPlanId: string,
  data: TestPlanGenerateReportRequest = {}
): Promise<ApiResponse<any>> {
  return request.post(`/test-plans/${testPlanId}/generate-report`, data).then(response => {
    if (response.data && response.data.success) {
      return response.data
    }
    throw new Error(response.data?.message || '生成测试报告失败')
  })
}

